package com.micro.ai.commons.aspect;

import com.micro.ai.commons.exception.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 参数验证切面
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Aspect
@Component
public class ValidationAspect {

    /**
     * 定义切点：所有Controller方法
     */
    @Pointcut("execution(* com.micro.ai..controller..*(..))")
    public void controllerPointcut() {
    }

    /**
     * 环绕通知：参数验证
     */
    @Around("controllerPointcut()")
    public Object validateParameters(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        
        // 检查是否有BindingResult参数
        for (Object arg : args) {
            if (arg instanceof BindingResult) {
                BindingResult bindingResult = (BindingResult) arg;
                if (bindingResult.hasErrors()) {
                    // 收集验证错误信息
                    Map<String, List<String>> errors = bindingResult.getFieldErrors().stream()
                            .collect(Collectors.groupingBy(
                                    FieldError::getField,
                                    Collectors.mapping(FieldError::getDefaultMessage, Collectors.toList())
                            ));
                    
                    log.warn("参数验证失败: {}", errors);
                    throw new ValidationException("参数验证失败", errors);
                }
            }
        }
        
        // 执行方法
        return joinPoint.proceed();
    }
}
